package com.qidian.server.workerThread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import com.qidian.common.Constants;
import com.qidian.server.messages.Message;
import com.qidian.server.messages.plugin2server.NumberTakingMessage;
import com.qidian.util.ByteUtil;


/**
 * 暂未使用
 * 
 * */
public class IDRegister extends WorkerThread
{
    
    private byte[] buffer = null;  
    
    private DatagramSocket socket = null;  

    private DatagramPacket recvPacket = null;  
  
    private InetSocketAddress socketAddress = null; 
    
    private long idSeq = -1L ;
    
    public IDRegister(String host, int port, long init_id) throws SocketException
    {
        socketAddress = new InetSocketAddress(host, port);  
        socket = new DatagramSocket(socketAddress);
        buffer = new byte[Constants.socket_buf_size] ;
        recvPacket = new DatagramPacket(buffer,buffer.length) ;
        idSeq = init_id ;
    }
    
    @Override
    public void init()
    {
        // TODO Auto-generated method stub
        
    }
    
    /**
     *  消息是否合法
     * 
     * */
    public boolean valid(DatagramPacket packet)
    {
        byte[] data = packet.getData() ;
        Message msg = null ;
        try
        {
            msg = Message.toMessage(data,0,data.length) ;
        }
        catch (Exception e)
        {
            e.printStackTrace() ;
            return false ;
        }
        if (!(msg instanceof NumberTakingMessage))
            return false ;
        return msg.isValid() ;
    }
    
    @Override
    public void run()
    {
        byte[] sendBuf = new byte[8] ;
        byte[] sendData = new byte[8] ;
        
        DatagramPacket sendPacket = new DatagramPacket(sendBuf,sendBuf.length);
        
        while(keepRunning)
        {
            try
            {
                socket.receive(recvPacket) ;
                
                
                if (!valid(recvPacket))
                    continue ;
                
                sendPacket.setSocketAddress(recvPacket.getSocketAddress()) ;
                ByteUtil.writeLong(sendData, 0, ++idSeq) ;
                sendPacket.setData(sendData) ;
                socket.send(sendPacket) ;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    

}
